<?php

require_once "lib/WxPay.Api.php";
require_once "WxPay.JsApiPay.php";
require_once 'lib/WxPay.Notify.php';
require_once "lib/WxPay.Data.php";

class Wxpay{
	public $site_id = 0;
	//构造函数
	public function Wxpay($site_id = 0){
		if($site_id == 0){
			$site_id = defined('__ADMINSITEID__')?__ADMINSITEID__:__RELATEID__;
		}
		
		$this->site_id = $site_id;
		
		$db = M('Payment');
		
		$ret = $db -> where(array('site_id' => $site_id,'classname' => 'Wxpay')) -> find();
		$ret = unserialize($ret['value']);
	    define('WX_APPID', $ret[0]);
		define('WX_MCHID', $ret[1]);
		define('WX_APPSECRET', $ret[2]);
		define('WX_KEY', $ret[3]);
		

		$mes = M('site')->where(array('id'=>$this->site_id))->find();
		$bonusconfig = unserialize($mes['bonusconfig']);
		// exit(dump($bonusconfig));
		define('WX_SSLCERT_PATH', $bonusconfig['apiclient_cert']);
		define('WX_SSLKEY_PATH', $bonusconfig['apiclient_key']);
		define('WX_CURL_PROXY_HOST', "0.0.0.0");
		define('WX_CURL_PROXY_PORT', 0);
		
		define('WX_REPORT_LEVENL', 0);
		
		
		
	}
	//创建设置项表单
	public function createform(){
		
		$db = M('Payment');
		$ret = array('','','','');
		$ret = $db -> where(array('site_id' => $this->site_id,'classname' => 'Wxpay')) -> find(); 
		$ret = unserialize($ret['value']);
		$html = '<style>#Wxpay td{padding:5px;}</style><table id="Wxpay" border="1" cellspacing="0" cellpadding="5" width="100%">
 
  <tr>
    <td align="center" valign="middle"><input type="hidden" name="classname" value="Wxpay">appid</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret[0].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle">mchid</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret[1].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle">appsecret</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret[2].'" /></td>
  </tr>
  <tr>
    <td align="center" valign="middle">key</td>
    <td align="center"><input type="text" name="level[]" value="'.$ret[3].'" /></td>
  </tr>
</table>';

        return $html;
	}
	
	//保存设置项
	public function saveform(){
		if(isset($_POST['level'])){
			$data['classname'] = 'Wxpay';
			$data['value'] = serialize($_POST['level']);
			$data['site_id'] = $this->site_id;
			$db = M('Payment');
			//dump($data);
			$ret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> find();
			if($ret){
				$saveret = $db -> where(array('site_id' => $data['site_id'],'classname' => $data['classname'])) -> data(array('value' => $data['value'])) -> save();
			}else{
				$saveret = $db -> data($data) -> add();
			}
			if($saveret){
				return true; 
			}else{
				return false;
			}
			
		}
	}
	
	//发起支付
	public function pay($orderid){
		/*require_once "lib/WxPay.Api.php";
		require_once "WxPay.JsApiPay.php";*/
		
		
		//①、获取用户openid
		$tools = new JsApiPay();
		$openId = $this->getOpenid($orderid);
		//$openId = 'othz_jnu0EOB8Q0Ts2RdrJ2CQduc';
		
		//获取商品信息
		$ordermes = M('order')->where(array('id'=>$orderid))->find();
		$Setbody = $ordermes['ordernumber'].$ordermes['id'];
		$SetTotal_fee = $ordermes['total']*100;
		
		//②、统一下单
		$input = new WxPayUnifiedOrder();
		
		
		
		$input->SetBody($ordermes['ordernumber']);
		$input->SetAttach($ordermes['ordernumber']);
		$input->SetOut_trade_no($ordermes['ordernumber']);
		$input->SetTotal_fee($SetTotal_fee);
		//$input->SetTotal_fee($SetTotal_fee);
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("test");
		//$input->SetNotify_url("http://www.sppcms.com/13/Payment/notify");
		$input->SetNotify_url("http://".$_SERVER['HTTP_HOST']. __APP__ ."/Payment/notify/code/Wxpay.html");
		$input->SetOpenid($openId);
		if(is_weixin()){
			$input->SetTrade_type("JSAPI");
		    $order = WxPayApi::unifiedOrder($input);
		    $jsApiParameters = $tools->GetJsApiParameters($order);
			$html = '<button class="btn btn-success btn-lg" id="payButton" type="button" onclick="callpay()" >立即支付</button>
			<script type="text/javascript">
			function jsApiCall()
			{
				document.getElementById("payPro").innerHTML = "正在处理，请稍等……";
				//document.getElementById("payButton").style.display = "none";
				WeixinJSBridge.invoke(
					"getBrandWCPayRequest",
					'.$jsApiParameters.',
					function(res){
						//WeixinJSBridge.log(res.err_msg);alert(res.err_msg);
						if(res.err_msg == "get_brand_wcpay_request:ok"){
							document.getElementById("payPro").innerHTML = "支付成功";
							document.getElementById("payButton").style.display = "none";
							paySuccess();
							//alert("支付成功");
						}else{
							
							document.getElementById("payPro").innerHTML = "点击按钮进行支付";
							document.getElementById("payButton").style.display = "block";
							if(res.err_msg == "get_brand_wcpay_request:fail"){
								document.getElementById("payPro").innerHTML = "支付错误！错误信息："+res.err_desc;
							}
						}
						//alert(res.err_code+res.err_desc+res.err_msg);
					}
				);
			}
		
			function callpay()
			{
				if (typeof WeixinJSBridge == "undefined"){
					if( document.addEventListener ){
						document.addEventListener("WeixinJSBridgeReady", jsApiCall, false);
					}else if (document.attachEvent){
						document.attachEvent("WeixinJSBridgeReady", jsApiCall); 
						document.attachEvent("onWeixinJSBridgeReady", jsApiCall);
					}
				}else{
					
					jsApiCall();
				}
			}
			
			callpay();
			</script>
			 ';
			
			
			
		}else{
			//$input = new WxPayUnifiedOrder();
			
			$input->SetTrade_type("NATIVE");
			$input->SetProduct_id($ordermes['ordernumber']);
		    $order = WxPayApi::unifiedOrder($input);
			$url = $order['code_url'];
			$html = '<div id="paycode" ><img src="'.U('Home/Ajax/qrcode').'&level=4&size=6&data='.$url.'"><p>请使用微信客户端扫描</p></div>
			
			<script>
    setInterval(function(){
		$.post("'.U('Home/Ajax/getOrderStatus').'",{id:'.$orderid.'}, function(data){
			if(data == 2){
				$("#paycode").html("支付成功");
				$("#payend").show();
				document.getElementById("payPro").innerHTML = "支付成功";
				paySuccess();
			}
		}, "html");
	}, 1000);
</script>';
			
			
		}
		
		
		
		
		
	    return $html;
		
	}
	
	
	
	public function callback(){
		
		$notify = new PayNotifyCallBack();
		$message = $notify->Handle(false);
		F('message',$message);
		return $message;
		
	}
	
	
	
	//获取openid
	public function getopenid($orderid){
	    
	   $order = M('order')->where(array('id'=>$orderid))->find();
	   $member_id = $order['member_id'];
	   $member = M('member')->where(array('id'=>$member_id))->find();
	   $openid = $member['openid'];
	   return $openid;
	   
	}
	
	// alicext 退款处理
	public function refund($sale_id,$refund_fee = 0){
		$sale = M('sale')->where(array('id'=>$sale_id))->find();
		$orderid = $sale['order_id'];

			//①、获取用户openid
		$tools = new JsApiPay();
		$openId = $this->getOpenid($orderid);
		
		//获取商品信息
		$ordermes = M('order')->where(array('id'=>$orderid))->find();
		$Setbody = $ordermes['ordernumber'].$ordermes['id'];
		$SetTotal_fee = $ordermes['total']*100;
		
		//②、统一下单
		$input = new WxPayRefund();
		$input->SetOut_trade_no($ordermes['ordernumber']);
		$input->SetTotal_fee($SetTotal_fee);
		$input->SetOut_refund_no($sale_id);
		$input->SetRefund_fee($refund_fee * 100);
		$input->SetOp_user_id(WX_MCHID);
		$refundResult = WxPayApi::refund($input);
		
		return $refundResult;
	}
	
	
	/**
	 * 
	 * 参数数组转换为url参数
	 * @param array $urlObj
	 */
	private function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			$buff .= $k . "=" . $v . "&";
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
}

	//微信回调
	
	//初始化日志
	class PayNotifyCallBack extends WxPayNotify
	{
		//查询订单
		public function Queryorder($transaction_id)
		{
			
			$input = new WxPayOrderQuery();
			$input->SetTransaction_id($transaction_id);
			$result = WxPayApi::orderQuery($input);
			F('transaction_id',$transaction_id);
			F('result',$result);
			if(array_key_exists("return_code", $result)
				&& array_key_exists("result_code", $result)
				&& $result["return_code"] == "SUCCESS"
				&& $result["result_code"] == "SUCCESS")
			{
				
				return true;
			}
			    return false;
		}
		
		//重写回调处理函数
		public function NotifyProcess($data, &$msg)
		{
			
			$notfiyOutput = array();
			
			if(!array_key_exists("transaction_id", $data)){
				$msg = "输入参数不正确";
				return false;
			}
			
			//查询订单，判断订单真实性
			if(!$this->Queryorder($data["transaction_id"])){
				$msg = "订单查询失败";
				return false;
			}
			    
			
			//微信支付	
		   if($data['result_code'] == 'SUCCESS'){
		      
			  $Order = D('Order');
			 $Order->upstate($data['out_trade_no']);
		   }
		   
		   return true;
			
		}
		
		
		

	
	
	}


